package com.liao.tensquare.handler;

import org.springframework.stereotype.Component;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class HeaderMapRequestWrapper extends HttpServletRequestWrapper {

    /**
     * 请求体
     */
    private final String mBody;

    public HeaderMapRequestWrapper(HttpServletRequest request) {
        super(request);
        // 将body数据存储起来
        mBody = getBody(request);
    }

    /**
     * 获取请求体
     * @param request 请求
     * @return 请求体
     */
    private String getBody(HttpServletRequest request) {
        try {
            byte[] data = new byte[1024];
            int length = 0;
            StringBuilder body = new StringBuilder();
            System.out.println(request.getInputStream().read(data));
//            while ((length = request.getInputStream().read(data)) != -1) {
//                System.out.println("length:"+length);
//            System.out.println(Arrays.toString(data));
                body.append(new String(data,0,length));
//            }
            System.out.println("body:"+new String(data));
            return body.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取请求体
     * @return 请求体
     */
    public String getBody() {
        return mBody;
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        // 创建字节数组输入流
        final ByteArrayInputStream bais = new ByteArrayInputStream(mBody.getBytes(Charset.defaultCharset()));

        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }
}
